﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using Mapster;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Entitys.Entity;
using SHZY.Business.Entitys.Common.Dto.PrintExecute;
using SHZY.Business.Entitys.Dto.customerappeal;
using SHZY.Business.Entitys.Dto.customerfile;
using SHZY.Business.Entitys.Dto.customermeasure;
using SHZY.Business.Entitys.Dto.customersurver;
using SHZY.Business.Entitys.Entity;
using SHZY.Business.Interfaces;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Manager.Files;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.FR;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.Business
{
    /// <summary>
    /// 业务实现：现场调查表.
    /// </summary>
    [ApiDescriptionSettings(Tag = "Business", Name = "QmsBusiCustomerSurvey", Order = 200)]
    [Route("api/Business/[controller]")]
    public class QmsBusiCustomerSurveyService : IQmsBusiCustomerSurveyService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<QmsBusiCustomerSurveyEntity> _repository;

        /// <summary>
        /// 数据接口服务.
        /// </summary>
        private readonly IDataInterfaceService _dataInterfaceService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 文件服务.
        /// </summary>
        private readonly IFileManager _fileManager;

        /// <summary>
        /// 初始化一个<see cref="QmsBusiCustomerSurveyService"/>类型的新实例.
        /// </summary>
        public QmsBusiCustomerSurveyService(
            ISqlSugarRepository<QmsBusiCustomerSurveyEntity> qmsBusiCustomerSurveyRepository,
            IDataInterfaceService dataInterfaceService,
            ISqlSugarClient context,
            IUserManager userManager, IFileManager fileManager)
        {
            _repository = qmsBusiCustomerSurveyRepository;
            _dataInterfaceService = dataInterfaceService;
            _userManager = userManager;
            _fileManager = fileManager;
        }

        /// <summary>
        /// 获取现场调查表.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var customerid = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == id).Select(it => new { id = it.Id }).FirstAsync();
            var customesurveydata = await _repository.Context.Queryable<QmsBusiCustomerSurveyEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.CustomerId == customerid.id).Select(it => new QmsBusiCustomerSurveyListOutput() {id = it.Id, projectName = it.ProjectName, orderNo = it.OrderNo, customerCode = it.CustomerCode, gdAddress = it.GdAddress, feedbackDate = it.FeedbackDate, feedbackRemark = it.FeedbackRemark, feedbackUserId = it.FeedbackUserId, process = it.Process, confirmedUserId = it.ConfirmedUserId, confirmedDate = it.ConfirmedDate, handledUserId = it.HandledUserId, handledDate = it.HandledDate, fIle = it.FIle, status = it.Status }).FirstAsync();
            if (customesurveydata == null)
            {
                customesurveydata = new QmsBusiCustomerSurveyListOutput() { id = "", projectName = "", orderNo = "", customerCode = "", gdAddress = "", feedbackDate = null ,feedbackRemark = "", feedbackUserId = "", process = "", confirmedUserId = "", confirmedDate = null, handledUserId = "", handledDate = null, fIle = "", status = "" };
            }
            return customesurveydata;
        }
        /// <summary>
        /// 新建现场调查表.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] QmsBusiCustomerSurveyCrInput input)
        {
            var entity = input.Adapt<QmsBusiCustomerSurveyEntity>();
            entity.Id = SnowflakeIdHelper.NextId();
            entity.EnabledMark = 1;
            var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
        }

        /// <summary>
        /// 更新现场调查表.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] QmsBusiCustomerSurveyUpInput input)
        {
            var entity = input.Adapt<QmsBusiCustomerSurveyEntity>();
            var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
            {
                it.ProjectName,
                it.OrderNo,
                it.CustomerCode,
                it.GdAddress,
                it.FeedbackDate,
                it.FeedbackRemark,
                it.FeedbackUserId,
                it.Process,
                it.ConfirmedUserId,
                it.ConfirmedDate,
                it.HandledUserId,
                it.HandledDate,
                it.FIle,
                it.Status,
                it.EnabledMark,
            }).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 打印现场调查表.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <param name="exportType">打印类型.</param>
        /// <returns></returns>
        [HttpPost("fastreportPrintCustomerSurvey")]
        public async Task<dynamic> PrintCustomerSurvey([FromBody] ComBasePrintExecuteCrInput input, FastReportExportType exportType = FastReportExportType.PDF)
        {
            //查询打印配置 获取打印模板文件和数据源SQL
            var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
            .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
            .Where(x => x.Id == input.printConfigId)
            .Select((x, a, b) => new
            {
                PrintTemplateId = x.PrintTemplateId,
                TemplateFileInfo = a.FileInfo,
                IsCustomer = x.IsCustomer,
                dbLinkId = b.DbLinkId,
                dataSql = b.SqlTemplate,
                labelRuler = x.LabelRulerTemplate
            }).FirstAsync();
            if (printConfigData == null)
                throw Oops.Bah("未查找到相关打印配置!");
            #region 查找打印模板文件路径

            string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
            // 判断是否匹配客户模板
            if (printConfigData.IsCustomer == 1)
            {
                var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
                    .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
                    .Select(s => s.FileInfo).FirstAsync();

                fileInfoJson = customerFile.ToString();
            }

            // 获取模板文件名
            string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
            string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

            #endregion
            //获取数据源
            var customeid = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == input.formDataId).Select(it => new QmsBusiCustomerComplaintEntity { Id = it.Id }).FirstAsync();
            var primary = await _repository.Context.Queryable<QmsBusiCustomerSurveyEntity>().Where(it => it.CustomerId == customeid.Id && it.DeleteMark == null).Select(it => new QmsBusiCustomerSurveyListOutput() 
            {
                id = it.Id, 
                projectName = it.ProjectName, 
                orderNo = it.OrderNo, 
                customerCode = it.CustomerCode, 
                gdAddress = it.GdAddress,
                _feedbackDate = it.FeedbackDate==null?"":SqlFunc.ToDate(it.FeedbackDate).ToString("yyyy-MM-dd"),
                feedbackRemark = it.FeedbackRemark, 
                feedbackUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.FeedbackUserId).Select(p => p.RealName),
                process = it.Process, 
                confirmedUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.ConfirmedUserId).Select(p => p.RealName),
                handledUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.HandledUserId).Select(p => p.RealName),
                _handledDate = it.HandledDate == null ? "" : SqlFunc.ToDate(it.HandledDate).ToString("yyyy-MM-dd"),
                fIle = it.FIle,
                status = it.Status,
                _confirmedDate = it.ConfirmedDate == null ? "" : SqlFunc.ToDate(it.ConfirmedDate).ToString("yyyy-MM-dd"),
            }).ToDataTableAsync();
            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
            {
                { "PrintData", primary },
            };
            FileResult ms = CreateFR.ExportLabelFastReport(filePath, dicList, exportType);
            return ms;
        }
    }
    //public class QmsBusiCustomerSurveyModel: QmsBusiCustomerSurveyListOutput
    //{
    //    /// <summary>
    //    /// 客户名称.
    //    /// </summary>
    //    public string customerName { get; set; }
    //    /// <summary>
    //    /// 反馈人.
    //    /// </summary>

    //    public string feedbackUserName { get; set; }
    //}
}
